package com.erytech.linktalk.web.server;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.erytech.linktalk.dao.domain.User;
import com.erytech.linktalk.web.client.service.LoginException;
import com.erytech.linktalk.web.client.service.UserInfo;
import com.erytech.linktalk.web.client.service.UserRpcService;

public class UserRpcServiceServlet extends BaseServlet implements
		UserRpcService {
	
	Log logger = LogFactory.getLog(UserRpcServiceServlet.class);

	public UserInfo login(UserInfo userInfo) throws LoginException {
		HttpSession session = getSession();
		User user = (User) session.getAttribute("user");
 		if(user == null) { //first login
 			logger.debug("Login..." + userInfo);
 			user = toUser(userInfo);
 			if(getServiceFacade().getUserManager().hasUser(user)) {
 				session.invalidate();
 				throw new LoginException("该用户名已存在!");
 			}
 			user = getServiceFacade().getUserManager().login(user);
 			session.setAttribute("user", user);
 			session.setMaxInactiveInterval(8);
 			session.setAttribute("daoFacade", getDaoFacade());
 			session.setAttribute("serviceFacade", getServiceFacade());
		} else {
			throw new LoginException("重复登录错误!");
		}
 		return toUserInfo(user);
	}

	public void logout() {
		HttpSession session = getSession();
		User user = (User) session.getAttribute("user");
		if (user == null) {
			logger.warn("still not login!");
			return;
		}
		getServiceFacade().getUserManager().logout(user);
		session.removeAttribute("user");
		session.removeAttribute("daoFacade");
		session.removeAttribute("serviceFacade");
		session.invalidate();
	}

	public UserInfo[] getUsers() {
		HttpSession session = getSession();
		User user = (User) session.getAttribute("user");
		if (user == null) {
			logger.warn("still not login!");
			return new UserInfo[0];
		}
		List userList = getDaoFacade().getUserDao().getUserList();
		List userInfoList = new ArrayList(userList.size());
		for (int i = 0; i < userList.size(); i++) {
			if( !user.getName().equals( ((User)userList.get(i)).getName() ) ) { 
				userInfoList.add(toUserInfo((User)userList.get(i)));
			}
		}
		return (UserInfo[])userInfoList.toArray(new UserInfo[userInfoList.size()]);
	}

}
